package service

import (
	"errors"
	"fmt"
	"sdc/repository/db/model"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type DonationService struct {
	db *gorm.DB
}

func NewDonationService(db *gorm.DB) *DonationService {
	return &DonationService{db: db}
}

// CreateDonation 创建捐款
func (s *DonationService) CreateDonation(donation *model.Donation) (string, error) {
	// 生成订单号
	orderNo := generateOrderNo()
	donation.OrderNo = orderNo

	err := s.db.Transaction(func(tx *gorm.DB) error {
		// 检查项目状态
		var project model.Project
		if err := tx.First(&project, donation.ProjectID).Error; err != nil {
			return err
		}
		if project.Status != 1 {
			return errors.New("项目状态不允许捐款")
		}

		// 创建捐款记录
		if err := tx.Create(donation).Error; err != nil {
			return err
		}

		// 更新项目金额（乐观锁）
		result := tx.Model(&project).
			Where("id = ? AND current_amount = ?", project.ID, project.CurrentAmount).
			Updates(map[string]interface{}{
				"current_amount": gorm.Expr("current_amount + ?", donation.Amount),
			})
		if result.RowsAffected == 0 {
			return errors.New("更新项目金额失败，请重试")
		}

		// 创建用户-项目关系
		relation := &model.UserProjectRelation{
			UserID:    donation.UserID,
			ProjectID: donation.ProjectID,
			Role:      2, // 2: 捐款人
		}
		return tx.Create(relation).Error
	})

	return orderNo, err
}

// 生成订单号
func generateOrderNo() string {
	return fmt.Sprintf("DON%s", uuid.New().String()[:8])
}
